package live.ciallo.discipline.controller;

import live.ciallo.discipline.pojo.Resoult;
import live.ciallo.discipline.pojo.TaskInfo;
import live.ciallo.discipline.task.TaskScheduler;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 任务处理
 */
@RestController
@RequestMapping("/api/task")
@AllArgsConstructor
public class TaskController {
    private final TaskScheduler taskScheduler;

    public static final List<TaskInfo> TASK_INFO_LIST = new CopyOnWriteArrayList<>();

    @GetMapping
    public Resoult<List<TaskInfo>> getTaskList() {
        return Resoult.success(TASK_INFO_LIST);
    }

    @PostMapping
    public Resoult<Boolean> setTaskList(@RequestBody List<TaskInfo> taskInfoList) {
        //按照时间从小到大排序
        taskInfoList.sort(Comparator.comparing(TaskInfo::getTime));
        TASK_INFO_LIST.clear();
        TASK_INFO_LIST.addAll(taskInfoList);
        taskScheduler.submitTasks(TASK_INFO_LIST);
        return Resoult.success(true);
    }
}
